<template>
  <div class="container">
    <el-row class="top-search">
      <el-col style="text-align: right;">
        <date-range-picker
          v-model="datePicker1"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="timeChange"
        />
        <el-select v-model="listQuery.langStr" size="small" class="w-140">
          <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select v-model="listQuery.mobileOrPc" size="small" class="w-140">
          <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>

        <el-button type="primary" icon="el-icon-search" size="small" @click="search()">搜索</el-button>
      </el-col>
    </el-row>
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activeName" type="card">
          <el-tab-pane label="资讯点击量统计" name="first">
            <div>
              <div class="title">
                <p>资讯点击量统计情况</p>
                <div class="btn">
                  <el-button class="fr m-l-10" size="small" @click="toExport('news_click_count')">导出</el-button>
                </div>
              </div>
              <div class="echart">
                <div id="news_click_count" :style="{width: '100%', height: '480px'}"/>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <div class="dividing-line" style="margin:10px 0; border: 1px solid #e6e6e6"/>

  </div>
</template>

<script>
import echarts from 'echarts';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import timeUtils from '@/utils/timeHandle.js';
import { exportJsonToExcel, formatJson } from '@/utils/excel/Export2Excel';
import {
  getNewsClickCountListApi
} from '@/api/user-analysis.js';

const HeadWithWeek = {
  news_click_count: [
    {
      prop: 'date',
      label: '日期'
    },
    {
      prop: 'shareNewsClickCount',
      label: '分析资讯点击次数（次）'
    },
    {
      prop: 'officailNewsClickCount',
      label: '官网资讯点击次数（次）'
    }
  ]

};
export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      tableName: {
        news_click_count: '资讯点击量统计'

      },
      dateType: {
        1: '(天)',
        2: '(周)',
        3: '(月)'
      },
      options1: [
        {
          value: '*',
          label: '全部'
        },
        {
          value: 'km',
          label: '柬文'
        },
        {
          value: 'ch',
          label: '中文'
        }
      ],
      options2: [
        {
          value: '*',
          label: '全部'
        },
        {
          value: 'mobile',
          label: '手机端'
        },
        {
          value: 'pc',
          label: '电脑端'
        }
      ],
      datePicker1: [
        timeUtils.timeHandle(new Date(new Date().getTime() - 6 * 24 * 3600000).getTime(), 'date'),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ],

      listQuery: {
        startTime: null,
        endTime: null,
        langStr: '*', // 操作语言  *,ch,km
        mobileOrPc: '*', // *,mobile,pc
        dateType: 1 // 1:日期; 2:周;3:月;
      },

      activeName: 'first',
      tableHead: null,
      list1: {
        date: [],
        dayOfWeek: [],
        shareNewsClickCount: [],
        officailNewsClickCount: []
      },
      xData: [], // 保存x轴数据
      legend: {
        1: ['分享点击量', '官网点击量']

      },
      exportData: {
        // 导出表格数据
        news_click_count: []

      },
      echartWidth: null,
      isFirstRender: true
    };
  },
  created() {

  },
  mounted() {
    this.getWidth();
    this.search();
  },
  methods: {

    timeChange(time) {
      if (!time) return;
      const startTime = Date.parse(time[0]);
      const endTime = Date.parse(time[1]);
      const Days = Math.floor(Math.abs(endTime - startTime) / (24 * 3600 * 1000));
      if (Days <= 31) {
        this.listQuery.dateType = 1;
      } else if (Days > 31 && Days <= 48) {
        this.listQuery.dateType = 2;
      } else if (Days > 48) {
        this.listQuery.dateType = 3;
      }
    },

    getWidth() {
      this.$nextTick(function() {
        this.echartWidth = this.$refs['tabs'].$el.clientWidth + 'px';
      });
    },

    search() {
      if (!this.datePicker1) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }

      this.listQuery.startTime = this.datePicker1[0];
      this.listQuery.endTime = this.datePicker1[1];

      this.getData1();
    },

    getData1() {
      // 分享点击量会员分析
      var myChart = echarts.init(document.getElementById('news_click_count'));
      myChart.showLoading();

      getNewsClickCountListApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const getData = res.data;
          this.exportData.news_click_count = res.data;

          Object.keys(this.list1).forEach(key => {
            this.list1[key] = getData.map(item => item[key]);
          });

          const that = this;
          that.xData = [];
          getData.forEach(function(item) {
            that.xData.push(item.date);
          });

          this.upDateEchart1();
        }
      });
    },

    upDateEchart1() {
      var myChart = echarts.init(document.getElementById('news_click_count'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {},
        legend: {
          data: this.legend[1],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            name: this.dateType[this.listQuery.dateType],
            nameTextStyle: {
              pnews_click_counting: [40, 0, 18, 0]
            },
            type: 'category',
            data: this.xData, // x轴数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            name: '(次)',
            type: 'value',
            min: 0,
            max: Math.ceil(Math.max(...this.list1['officailNewsClickCount'])),
            interval: Math.ceil(Math.max(...this.list1['officailNewsClickCount']) / 5),
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            name: '(次)',
            type: 'value',
            min: 0,
            max: Math.ceil(Math.max(...this.list1['shareNewsClickCount'])),
            interval: Math.ceil(Math.max(...this.list1['shareNewsClickCount']) / 5),
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '分享点击量',
            type: 'line',
            data: this.list1['officailNewsClickCount']
          },
          {
            name: '官网点击量',
            type: 'line',
            data: this.list1['shareNewsClickCount'],
            yAxisIndex: 1
          }
        ]
      };
      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    toExport(exportName) {
      this.tableHead = HeadWithWeek;

      const exprtTime = timeUtils.timeHandle(new Date().getTime(), 'date');
      const tHeader = this.tableHead[exportName].map(item => item.label);
      const tKey = this.tableHead[exportName].map(item => item.prop);
      const data = formatJson(tKey, this.exportData[exportName]); // 数据格式化
      const fileName = this.tableName[exportName] + exprtTime;
      exportJsonToExcel(tHeader, data, fileName); // 导出文件
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
    margin: 15px;
  .w-140 {
    width: 140px;
  }
  .w-240 {
    width: 240px;
  }
  .title {
    height: 32px;
    position: relative;
    p {
      font-size: 22px;
      line-height: 32px;
      text-align: center;
    }
    .btn {
      width: 400px;
      height: 32px;
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  .echart {
    width: 100%;
  }
  .search {
    text-align: right;
    pnews_click_counting: 15px;
    background-color: rgba(240, 242, 245, 1);
  }
  // 底部的echart
  .bottom-echart {
    .echart {
      position: relative;
      width: 45%;
      float: left;
      margin: 20px;
      .title {
        height: 32px;
        position: relative;
        p {
          font-size: 22px;
          line-height: 32px;
          text-align: center;
        }
        .btn {
          width: 400px;
          height: 32px;
          position: absolute;
          right: 0;
          top: 0;
        }
      }
      .num {
        position: absolute;
        right: 50px;
        bottom: 100px;
        li {
          font-size: 14px;
          line-height: 24px;
          span {
            pnews_click_counting: 0 10px;
          }
          .vertical {
            pnews_click_counting: 0;
            height: 24px;
            width: 1px;
            border: 1px solid #eee;
          }
        }
      }
      .list {
        width: 508px;
        pnews_click_counting-top: 20px;
        float: right;
        li {
          display: flex;
          justify-content: space-between;

          font-size: 22px;
          line-height: 48px;
          border-bottom: 1px solid #ccc;
        }
        .list-title {
          font-size: 18px;
          line-height: 56px;
        }
      }
    }
  }
}
</style>
